package com.csproj.basic.resource;

import com.codahale.metrics.annotation.Timed;
import com.csproj.basic.service.CollarRecordService;
import com.csproj.basic.service.PDAService;
import com.csproj.basic.service.dto.PDADTO;
import com.csproj.siiat.base.common.dto.BaseDTO;
import com.csproj.siiat.base.common.repository.PageableTools;
import com.csproj.siiat.base.common.repository.SortDto;
import com.csproj.system.domain.UserInfo;
import com.csproj.system.service.SysLogsService;
import com.csproj.system.service.UserInfoService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.net.URISyntaxException;
import java.time.ZonedDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * REST controller for managing PDA.
 */
@RestController
@RequestMapping("/api/siiat/v1")
public class PDAResource {

    private final Logger log = LoggerFactory.getLogger(PDAResource.class);


    private final PDAService pdaService;
    private final CollarRecordService collarRecordService;
    private final UserInfoService userInfoService;
    private final SysLogsService sysLogsService;

    public PDAResource(PDAService pdaService, CollarRecordService collarRecordService,SysLogsService sysLogsService,
    UserInfoService userInfoService) {
        this.pdaService = pdaService;
        this.collarRecordService = collarRecordService;
        this.userInfoService = userInfoService;
        this.sysLogsService = sysLogsService;
    }


    /**
     * POST  /pdas : 创建pda
     * @param pdaDto pdaDTO
     * @return
     * TODO 保存post方法
     * TODO 每个方面里面都要加try catch处理
     */
    @PostMapping("/pdas")
    @Timed
    public BaseDTO createPda(@Valid @RequestBody PDADTO pdaDto){
        PDADTO result = pdaService.saveAndGetDTO(pdaDto);

        UserInfo userInfo = userInfoService.getCurrentUser();
        sysLogsService.saveForGet("", userInfo.getName()+":user_create_pda","");
        return BaseDTO.createBaseDTO().setData(result);
    }

    /**
     * PUT  /pdas : 修改pda信息.
     * @param pdaDTO  pdaDTO
     * @return
     */
    @PutMapping("/pdas/{id}")
    @Timed
    public BaseDTO updatePda(@Valid @RequestBody PDADTO pdaDTO, @PathVariable String id) throws URISyntaxException {
        pdaDTO.setId(id);
        PDADTO result = pdaService.updateAndGetDTO(pdaDTO);

        UserInfo userInfo = userInfoService.getCurrentUser();
        sysLogsService.saveForGet("", userInfo.getName()+":user_update_pda","");
        return BaseDTO.createBaseDTO().setData(result);
    }

    /**
     * GET  /pdas : 获取pda信息.
     * @return pda信息
     */
    @GetMapping("/pdas")
    @Timed
    public BaseDTO getPagePDAs(@RequestParam(value = "pageNumber",required = false) Integer pageNum,
                                @RequestParam(value = "pageSize",required = false) Integer pageSize,
                               @RequestParam(value = "siteId",required = false) String siteId,
                                @RequestParam(value = "pdaNo",required = false) String pdaNo) {
        Pageable pageable = PageableTools.basicPage(pageNum,pageSize);
        Map<String,Object> map = new HashMap<>();
        map.put("pdaNo",pdaNo);
        map.put("siteId",siteId);
        BaseDTO result = pdaService.findPageListAndGetDTO(map,pageable);
        UserInfo userInfo = userInfoService.getCurrentUser();
        Object as = sysLogsService.saveForGet("", userInfo.getName()+":user_get_pda_list","");
        int i = 0;
        return result;
    }

    /**
     *
     */
    @GetMapping("/pdas/")
    public BaseDTO getPDAsWithPage(@RequestParam(value = "pageNumber",required = false) Integer pageNum,
                                   @RequestParam(value = "pageSize",required = false) Integer pageSize,
                                   @RequestParam(value = "siteId",required = false) String siteId,
                                   @RequestParam(value = "pdaNo",required = false) String pdaNo){

        SortDto sortDto = new SortDto("DESC","creationTime");
        Pageable pageable = PageableTools.basicPage(pageNum,pageSize,sortDto);
        Map<String,Object> map = new HashMap<>();
        map.put("pdaNo",pdaNo);
        map.put("siteId",siteId);
        BaseDTO result = pdaService.findPageListAndGetDTO(map,pageable);

        UserInfo userInfo = userInfoService.getCurrentUser();
        sysLogsService.saveForGet("", userInfo.getName()+":user_get_pda_list","");
        return result;

    }

    /**
     *
     * 查询领用记录
     */
    @GetMapping("/pads/{id}/collarRecords")
    public BaseDTO getCollarRecordsWithPage(@PathVariable String id,
                                            @RequestParam(value = "name",required = false) String name,
                                            @RequestParam(value = "pageNumber",required = false) Integer pageNum,
                                            @RequestParam(value = "pageSize",required = false) Integer pageSize,
                                            @RequestParam(value = "startTime",required = false) ZonedDateTime startTime,
                                            @RequestParam(value = "endTIme",required = false) ZonedDateTime endTime){
        SortDto sortDto = new SortDto("desc","cr.creationTime");
        Pageable pageable = PageableTools.basicPage(pageNum,pageSize,sortDto);
        Map<String,Object> map = new HashMap<>();
        if(StringUtils.isNotBlank(name)){
            map.put("name",name);
        }
        if(startTime!=null){
            map.put("startTime",startTime);
        }
        if(endTime!=null){
           map.put("endTime",endTime);
        }

        BaseDTO result = collarRecordService.findPageListByDeviceId(id,map,pageable);


        UserInfo userInfo = userInfoService.getCurrentUser();
        sysLogsService.saveForGet("", userInfo.getName()+":user_get_collar_list","");
        return result;
    }


    /**
     * GET  /pdas : 获取pda信息(不分页)
     * @return BaseDTO
     */
    @GetMapping("/allpdas")
    @Timed
    public BaseDTO getAllPDAs() {
        return BaseDTO.createBaseDTOByFieldList(pdaService.findAll());
    }

    /**
     * GET  /pdas/:id : 根据机构id，获取机构信息
     *
     * @param id pdaid
     * @return pda信息
     */
    @GetMapping("/pdas/{id}")
    @Timed
    public BaseDTO getPDA(@PathVariable String id) {
        PDADTO pdadto = pdaService.findOneAndGetDTO(id);
        return BaseDTO.createBaseDTO().setData(pdadto);
    }

    /**
     * DELETE  /pdas/:id : 根据id，删除pda信息.
     * @param id id
     * @return
     */
    @DeleteMapping("/pdas/{id}")
    @Timed
    public BaseDTO deletePda(@PathVariable String id) {
        pdaService.delete(id);
        return BaseDTO.createBaseDTO().setMessage("delete_success");
    }

    /**
     * PUT  /pdas/updatePdaStatus/{id} : 修改pda使用状态
     *
     * @param pdadto
     * @param id
     * @return BaseDTO
     * @throws URISyntaxException
     */
    @PutMapping("/pdas/updatePdaStatus/{id}")
    @Timed
    public BaseDTO updatePdaStatus(HttpServletRequest request, @RequestBody(required = false) PDADTO pdadto,@PathVariable String id) throws URISyntaxException {
        log.debug("REST request to update UserInfo isUse : {}", pdadto);
        pdadto.setId(id);
        PDADTO result = pdaService.updatePdaStatus(pdadto);

        UserInfo userInfo = userInfoService.getCurrentUser();
        sysLogsService.saveForGet("", userInfo.getName()+":user_update_pda_status","");
        return BaseDTO.createBaseDTO(result).setMessage("user_update_pda_status_success");
    }
    /**
     * PUT  /pdas/updateEnable/{id} : 修改PDA使用状态
     *
     * @param dto
     * @param id
     * @return BaseDTO
     * @throws URISyntaxException
     */
    @PutMapping("/pdas/updateEnable/{id}")
    @Timed
    public BaseDTO updatePdaEnable(HttpServletRequest request, @RequestBody(required = false) PDADTO dto, @PathVariable String id) throws URISyntaxException {
        dto.setId(id);
        if (dto.getId() == null) {
            return createPda(dto);
        }
        PDADTO result = pdaService.status(dto.getId(),dto.isEnableFlag());
        UserInfo userInfo = userInfoService.getCurrentUser();
        sysLogsService.saveForGet("", userInfo.getName()+":user_update_pda_status","");
        return BaseDTO.createBaseDTO(result).setMessage("user_update_pda_status_success！");
    }

    /**
     * 获取统计数量（库存与已归还）
     * @return
     */
    @GetMapping("/pdas/statistics")
    @Timed
    public BaseDTO getPdaStatistics(){
        Map<String,Object> result = pdaService.getPdaStatistics();
        return BaseDTO.createBaseDTO(result);
    }

    /**
     *  批量导入
     */
    @PostMapping("/pdas/batchImport")
    @Timed
    public BaseDTO pdafixBatchImport(MultipartFile file){
        UserInfo userInfo = userInfoService.getCurrentUser();
        sysLogsService.saveForGet("", userInfo.getName()+":user_pda_batch_import","");
        return pdaService.batchImport(file) ;
    }
}